from docx import Document
from docx.oxml.ns import qn
from docx.shared import Pt,RGBColor,Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
import datetime

class DocHandle:
    def __init__(self):
        return

    def create_doc(self, savePath, titleName, paraList, imageList, excelName, excelinfo):
        document = Document()
        # 文本格式
        document.styles['Normal'].font.name = u"宋体"
        document.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'),u'宋体')
        # 标题名称
        self.add_doc_titleName(document, titleName)
        # 段落格式设置
        self.add_doc_paragraphs(document, paraList)
        # 插入图片
        self.add_doc_images(document, imageList)
        # 创建时间
        self.add_doc_create_time(document)
        # 插入表格
        self.add_doc_excel(document, excelName, excelinfo)

        document.save(savePath)
        print("save doc file success: " + savePath)
        return

    def add_doc_titleName(document, titleName):
        title = document.add_heading(0)
        title.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = title.add_run(titleName)
        run.font.name = u"宋体"
        run.font.size = Pt(22)
        run._element.rPr.rFonts.set(qn('w:eastAsia'),u'宋体')
        run.font.bold = True
        run.font.color.rgb = RGBColor(0,0,0)
        return

    def add_doc_paragraphs(document, paraList):
        # 段落格式设置
        paragraphs = []
        for para in paraList:
            paragraphs.append(document.add_paragraph(para))
        for para in paragraphs:
            para.space_after = Pt(5)
            para.space_before = Pt(5)
            for run in para.runs:
                run.font.name = u"宋体"
                run.font.size = Pt(12)
                run._element.rPr.rFonts.set(qn('w:eastAsia'),u'宋体')
        return

    def add_doc_images(document, imageList):
        # 插入图片
        for image in imageList:
            p_img = document.add_paragraph()
            p_img.alignment = WD_ALIGN_PARAGRAPH.CENTER
            p_run_img = p_img.add_run()
            img_obj = p_run_img.add_picture(image, width=Inches(5))
        return

    def add_doc_excel(document, excelName, excelinfo):
        document.add_page_break()
        title = document.add_heading(0)
        title.alignment = WD_ALIGN_PARAGRAPH.CENTER
        run = title.add_run(excelName)
        run.font.name = u"宋体"
        run.font.size = Pt(22)
        run._element.rPr.rFonts.set(qn('w:eastAsia'),u'宋体')
        run.font.bold = True
        run.font.color.rgb = RGBColor(0,0,0)
        # 插入表格
        if len(excelinfo) == 0:
            return
        row = len(excelinfo)
        col = len(excelinfo[0])
        table = document.add_table(rows=row,cols=col)
        table.style = 'Light Shading'
        for r in range(row):
            for c in range(col):
                table.cell(r,c).text = excelinfo[r][c]
        return

    def add_doc_create_time(document):
        # 文章结尾
        paragraph = document.add_paragraph()
        paragraph.space_after = Pt(5)
        paragraph.space_before = Pt(5)
        paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
        paragraph.add_run("此文档生成于")

        today = datetime.datetime.now()
        today = today.strftime(" %Y{}%m{}%d{} ").format('年','月','日')
        timerun = paragraph.add_run(today)
        timerun.font.name = u"宋体"
        timerun.font.size = Pt(13)
        timerun._element.rPr.rFonts.set(qn('w:eastAsia'),u'宋体')
        return

# 文件解析和比较
if __name__ == "__main__":
    docHandle = DocHandle()
    paragraphs = ['那年冬天，祖母死了，父亲的差使也交卸了，正是祸不单行的日子。我从北京到徐州，'
                                         '打算跟着父亲奔丧回家。到徐州见着父亲，看见满院狼藉的东西，又想起祖母，不禁'
                                         '簌簌地流下眼泪。父亲说：“事已如此，不必难过，好在天无绝人之路！”',
                  '回家变卖典质，父亲还了亏空；又借钱办了丧事。这些日子，家中光景很是惨澹，一'
                                         '半为了丧事，一半为了父亲赋闲。丧事完毕，父亲要到南京谋事，我也要回北京念书'
                                         '，我们便同行。',
                  '到南京时，有朋友约去游逛，勾留7了一日；第二日上午便须渡江到浦口，下午上车'
                                         '北去。父亲因为事忙，本已说定不送我，叫旅馆里一个熟识的茶房陪我同去。他再三'
                                         '嘱咐茶房，甚是仔细。但他终于不放心，怕茶房不妥帖；颇踌躇了一会。其实我那年'
                                         '已二十岁，北京已来往过两三次，是没有什么要紧的了。他踌躇了一会，终于决定还'
                                         '是自己送我去。我再三劝他不必去；他只说：“不要紧，他们去不好！”',
                  '我们过了江，进了车站。我买票，他忙着照看行李。行李太多，得向脚夫行些小费才'
                                         '可过去。他便又忙着和他们讲价钱。我那时真是聪明过分，总觉他说话不大漂亮，非'
                                         '自己插嘴不可，但他终于讲定了价钱；就送我上车。他给我拣定了靠车门的一张椅子；'
                                         '我将他给我做的紫毛大衣铺好座位。他嘱我路上小心，夜里要警醒些，不要受凉。又'
                                         '嘱托茶房好好照应我。我心里暗笑他的迂；他们只认得钱，托他们只是白托！而且我'
                                         '这样大年纪的人，难道还不能料理自己么？我现在想想，我那时真是太聪明了。'
    ]
    imageList = []
    excelinfo = []
    docHandle.create_doc("test.docx", "背影", paragraphs, imageList, "表格1", excelinfo)